package br.com.massai.view.utils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import br.com.massai.model.entity.Action;
import br.com.massai.model.entity.Collaborator;
import br.com.massai.model.entity.Function;
import br.com.massai.model.entity.Url;
import br.com.massai.model.exceptions.SystemException;
import br.com.massai.view.enums.Role;

public class MassaiUtil implements Serializable {

	private static final long serialVersionUID = 5923638052021970949L;

	public static final String USER_LOGGED = "massai.user";
	public static final String USER_PERMISSIONS = "massai.permission";
	public static final String USER_ACTIONS = "massai.action";

	public static Collaborator getUserLogged() throws SystemException {
		return (Collaborator) FacesUtil.obterAtributoSessao(USER_LOGGED);
	}
	
	public static String getNameUser() throws SystemException {
		Collaborator c = getUserLogged();
		if(c != null && c.getId() != null)
			return c.getNameCollaborator();
		return "ADMINISTRADOR";
	}

	public static boolean isLogIn() {
		if(getUserLogged() != null && getUserLogged().getId() != null)
			return true;
		return false;
	}

	public static boolean isAdmin() throws SystemException {
		if(getUserLogged() != null && getUserLogged().getRole().equals(Role.A))
			return true;
		return false;
	}

	public static List<Url> urlPermissions() throws SystemException {
		return urlByUser();
	}

	private static List<Url> urlByUser() throws SystemException {
		List<Url> urls = new ArrayList<Url>();
		for(Function f : functionsByUser()){
			for(Url u : f.getUrls()){
				if(!urls.contains(u))
					urls.add(u);
			}
		}
		return urls;
	}
	
	public static List<Function> functionsByUser() throws SystemException {
		List<Function> functions = new ArrayList<Function>();
		if(getUserLogged() != null)
			for(Action a : getUserLogged().getActions())
				if(!functions.contains(a.getFunction()))
					functions.add(a.getFunction());
		return functions;
	}
}